package cn.tedu.forum.commons.response;

import cn.tedu.forum.commons.exception.ServiceException;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
public class JsonResponse<T> {
    @ApiModelProperty(value = "业务状态码", position = 1)
    private Integer state; // 业务返回码
    @ApiModelProperty(value = "消息", position = 2)
    private String message; // 消息
    @ApiModelProperty(value = "数据", position = 3)
    private T data; // 数据

    // 写一个私有构造方法代表不希望通过new创建此类的对象，而是通过自定义的静态方法来创建，从而限制state的值
    private JsonResponse() {
    }

    public static JsonResponse<Void> ok() {
        return ok(null); // 方法体非常相似时，参数少的调用参数多的
    }

    public static <T> JsonResponse<T> ok(T data) {
        JsonResponse<T> jsonResponse = new JsonResponse<>();
        jsonResponse.state = ServiceCode.OK.getValue();
        jsonResponse.data = data;
        return jsonResponse;
    }

    public static JsonResponse<Void> fail(ServiceException e) {
        return fail(e.getServiceCode(), e.getMessage());
    }

    public static JsonResponse<Void> fail(ServiceCode serviceCode, String message) {
        JsonResponse<Void> jsonResponse = new JsonResponse<>();
        jsonResponse.state = serviceCode.getValue();
        jsonResponse.message = message;
        return jsonResponse;
    }

}
